﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Xml;

using FRL.DebtChased.Extensions;

namespace FRL.DebtChased.Repository
{

	/// <summary>
	/// Extensions to the ClientWorkflowAssignments model
	/// </summary>
	public partial class ClientWorkflowAssignments
	{

		/////////////////////////////////////////////////////////////
		// Static Operations

		public static string Set( DebtChasedEntities ent, Dictionary<int, int> assignmentMap, int iClientId, int iUserId )
		{

			// Declare return variable
			string strError = null;

			try
			{

				// Get the existing assignments
				List<ClientWorkflowAssignment> current = (from wa in ent.ClientWorkflowAssignments where (wa.ClientId == iClientId) select wa).ToList();

				// Change existing assignments
				foreach (ClientWorkflowAssignment cwa in current)
				{

					// Get the workflow mapping
					int? iWorkflowId = null;
					if (assignmentMap.ContainsKey(cwa.AccountInvoiceStatusId))
					{
						iWorkflowId = assignmentMap[cwa.AccountInvoiceStatusId];
						if (iWorkflowId == 0)
							iWorkflowId = null;
					}

					// If record needs changing...
					if (iWorkflowId != cwa.WorkflowId)
					{
						cwa.WorkflowId = iWorkflowId;
					}

				}

				// Add new assignments
				foreach (var di in assignmentMap)
				{

					// Ignore if this is a zero
					if (di.Value == 0)
						continue;

					// Find a matching record
					bool bFound = false;
					foreach (ClientWorkflowAssignment wa in current)
					{
						if (wa.AccountInvoiceStatusId == di.Key)
						{
							bFound = true;
							break;
						}
					}

					// If record not found...
					if (!bFound)
					{
						ClientWorkflowAssignment newAssignment = ClientWorkflowAssignment.CreateClientWorkflowAssignment(0, iClientId, di.Key);
						newAssignment.WorkflowId = di.Value;
						newAssignment.ClientId = iClientId;
						ent.ClientWorkflowAssignments.AddObject(newAssignment);
					}

				}

				// Save changes to database
				ent.SaveChanges();

			}
			catch (Exception x)
			{

				// Update error
				strError = string.Format("Failed to save workflow assignemnts.  {0}", Definitions.SeeErrorLog);

				// Log the error
				ErrorLog.Add(ent, "Saving workflow assignments", x, iUserId);

			}

			// Return variable
			return strError;

		}

		public static int? GetWorkflowId(DebtChasedEntities ent, int iClientId, int iAccountInvoiceStatusId)
		{

			// Load from table
			int? iFtmp = (from cwa in ent.ClientWorkflowAssignments
							  where (cwa.ClientId == iClientId) && (cwa.AccountInvoiceStatusId == iAccountInvoiceStatusId)
							  select cwa.WorkflowId).FirstOrDefault();

			// Return variable
			return iFtmp;

		}

	}

}
